package com.deer.wms.system.manage.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.deer.wms.intercept.annotation.User;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.core.result.Result;
import com.deer.wms.project.root.core.result.ResultGenerator;
import com.deer.wms.project.root.exception.ServiceException;
import com.deer.wms.system.manage.model.dept.Dept;
import com.deer.wms.system.manage.model.dept.DeptCriteria;
import com.deer.wms.system.manage.model.dept.DeptDto;
import com.deer.wms.system.manage.model.dept.DeptVo;
import com.deer.wms.system.manage.model.poi.ExcelUtils;
import com.deer.wms.system.manage.model.user.UserInfo;
import com.deer.wms.system.manage.model.user.UserInfoDto;
import com.deer.wms.system.manage.model.user.UserVo;
import com.deer.wms.system.manage.service.DeptService;
import com.deer.wms.system.manage.service.UserInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;

/**
 * @author guo
 * @since 2019/11/05
 */
@Api(description = "部门信息api接口")
@RestController
@RequestMapping("/depts")
public class DeptController {

    @Autowired
    private DeptService deptService;

    @Autowired
    private UserInfoService userInfoService;




    @PostMapping("/insert")
    @ApiOperation(value = "添加部门信息", notes = "添加部门信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })

    public Result add(@RequestBody DeptDto dept, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        deptService.createDept(dept, currentUser);
        return ResultGenerator.genSuccessResult();
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @Transactional
    @GetMapping("/delete")
    @ApiOperation(value = "删除部门信息", notes = "删除部门信息")
    public Result delete(Integer deptId, @ApiIgnore @User CurrentUser currentUser) {

        List<UserInfoDto> userInfos = userInfoService.findByDeptId(deptId);
        if (userInfos.size() == 0) {
            Integer parentId = deptId;
            List<Dept> depts = deptService.findByParentId(parentId);
            for (Dept dept : depts) {
                deptService.removeById(dept.getDeptId());
            }
            deptService.removeById(deptId);
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(CommonCode.DEPT_BOUND, null);
        }
    }

    @Transactional
    @PostMapping("/update")
    @ApiOperation(value = "更新部门信息", notes = "更新部门信息")
    public Result update(@RequestBody Dept dept) {
        List<DeptDto> list = deptService.findByDeptCode(dept.getDeptCode());
        if (list.size() == 0) {
            deptService.updateById(dept);
        } else if (list.size() == 1) {
            if (list.get(0).getDeptId().equals(dept.getDeptId())) {
                List<DeptDto> list1 = deptService.findByDeptName(dept.getDeptName());
                if (list1.size() == 0) {
                    deptService.updateById(dept);
                } else if (list1.size() == 1 && list1.get(0).getDeptId().equals(dept.getDeptId())) {
                    deptService.updateById(dept);
                } else {
                    throw new ServiceException(CommonCode.DEPT_EXISTS, "此部门已存在");
                }

            } else if (!list.get(0).getDeptId().equals(dept.getDeptId())) {
                throw new ServiceException(CommonCode.DEPT_CODE_EXISTS, "此部门编码已存在");
            }
        }
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/detail")
    @ApiOperation(value = "单个部门查询", notes = "单个部门查询")
    public Result detail(Integer id) {
        Dept dept = deptService.getById(id);
        return ResultGenerator.genSuccessResult(dept);
    }


    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @GetMapping("/list")
    public Result list(DeptCriteria criteria, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        if (currentUser.getIsAdmin() == 1) {
            criteria.setUserId(null);
        }
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<DeptDto> list = deptService.findList(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }


    @GetMapping("/treeParentList")
    @ApiOperation(value = "treeParentList", notes = "treeParentList")
    public Result list(Dept dept) {
        List<Dept> depts = deptService.list();
        List<Integer> list = deptService.treeParentList(depts, dept);
        return ResultGenerator.genSuccessResult(list);
    }

    @GetMapping("/treeDept/{pid}")
    @ApiOperation(value = "部门树表")
    public Result treeDept(@PathVariable(value = "pid") Integer pid) {
        return ResultGenerator.genSuccessResult(deptService.list(new QueryWrapper<Dept>().eq("enabled", 1)));

    }

    /**
     * 导入
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public Result importUser(@RequestPart("file") MultipartFile file) throws Exception {
        List<DeptVo> deptVos = ExcelUtils.readMultipartFile(file, DeptVo.class);
        deptVos.stream().forEach(t->{
            Dept one = deptService.getOne(new LambdaQueryWrapper<Dept>().eq(Dept::getErpDeptId, t.getErpDeptId()));
            if (one == null){
                Dept dept = new Dept();
                dept.setDeptCode(t.getDeptCode());
                dept.setDeptName(t.getDeptName());
                dept.setErpDeptId(t.getErpDeptId());
                dept.setOrg(t.getOrg());
                deptService.save(dept);
            }
        });
        return ResultGenerator.genSuccessResult();
    }
}
